package com.xexun.gpstracker.my.activity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.*;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.base.CommTitleActivity;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.inter.CommDialogListener;
import com.xexun.gpstracker.inter.HttpCallback;
import com.xexun.gpstracker.listener.PrettyTextChangeListener;
import com.xexun.gpstracker.pojo.Device;
import com.xexun.gpstracker.pojo.ResponseData;
import com.xexun.gpstracker.pojo.TermFriend;
import com.xexun.gpstracker.util.CommUtil;
import com.xexun.gpstracker.util.Utils;
import com.xexun.gpstracker.vo.Session;

/**
 * Created by Admin on 2015/9/9
 */
public class AddGoodFriendsActivity extends CommTitleActivity {

    @ViewInject(R.id.friends_name_et)
    private EditText friendsName;
    @ViewInject(R.id.friends_phone_et)
    private EditText friendsPhone;
    //    @ViewInject(R.id.friends_relationship_et)
//    private EditText friendsRelationship;
    @ViewInject(R.id.imb_select_pic)
    private ImageButton imbSelectPic;
    @ViewInject(R.id.friends_relationship_spi)
    private Spinner friendsRelationshipSpi;

    @ViewInject(R.id.friends_term)
    private Spinner friendsTerm;

    private TermFriend mFriends;
//    private Keeper mKeeper;
    private ArrayAdapter relationAdapter;
    private ArrayAdapter<String> friendsTermAdapter;

    private String name;
    private String phone;
    private String relationship;
    private String imeis = "";
//    private List<String> relationIds;
    private List<String> relationFIds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载内容布局
        setContentViewAddTop(R.layout.activity_add_goog_friends);
        complet.setVisibility(View.VISIBLE);
        moreFunction.setVisibility(View.GONE);
        x.view().inject(this);
        mFriends = new TermFriend();

        //下拉列表数据处理
        relationAdapter = ArrayAdapter.createFromResource(this, R.array.relation_friend, R.layout.item_spinner_friend);
        relationAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        friendsRelationshipSpi.setAdapter(relationAdapter);
//        relationIds= Arrays.asList(getResources().getStringArray(R.array.relation_family_id));
        relationFIds= Arrays.asList(getResources().getStringArray(R.array.relation_friend_id));

        //好友终端
        List<Device> devices = Session.getInstance().getMonitors();
        List<String> deviceNames = new ArrayList<>();
        deviceNames.add(getString(R.string.pl_select));
        for (Device device : devices) {
            deviceNames.add(device.getName());
        }
        friendsTermAdapter = new ArrayAdapter<>(this, R.layout.spinner_item, deviceNames);
        friendsTermAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        friendsTerm.setAdapter(friendsTermAdapter);

        initEvent();
        initData();
    }

    private void initData() {
//        mKeeper = (Keeper) getIntent().getSerializableExtra("keep");
        mFriends = (TermFriend) getIntent().getSerializableExtra("friend");
//        if (mKeeper != null) {
//            /*friendsName.setText(CommUtil.isBlank(mKeeper.getNickName())?"未设置昵称":mKeeper.getNickName());
//            friendsPhone.setText(CommUtil.isBlank(mKeeper.getCellPhone())?CommUtil.isBlank(mKeeper.getName())?"未设置电话号码":mKeeper.getName().substring(0,mKeeper.getName().length()-3):mKeeper.getCellPhone());
//            friendsRelationship.setText(CommUtil.isBlank(mKeeper.getAppIdentity())?"未选定关系":mKeeper.getAppIdentity());*/
//            Log.i(Constants.TAG, mKeeper.toString());
//            title.setText(getString(R.string.add_friends_message));
//            if(mKeeper.getAppIdentity().contains(".")){
//                friendsRelationshipSpi.setSelection(relationIds.indexOf(mKeeper.getAppIdentity()));
//            }else {
//                friendsRelationshipSpi.setSelection(relationAdapter.getPosition(mKeeper.getAppIdentity()));
//            }
//            friendsName.setText(mKeeper.getNickName());
//            friendsPhone.setText(CommUtil.prettyString(mKeeper.getCellPhone(), null, true, 3, 4));
//            //friendsRelationship.setText(mKeeper.getAppIdentity());
//        } else
        if (mFriends != null) {
            Log.i(Constants.TAG, mFriends.toString());
            title.setText(getString(R.string.add_friends_message));
            if(mFriends.getRelationship().contains(".")){
                friendsRelationshipSpi.setSelection(relationFIds.indexOf(mFriends.getRelationship()));
            }else {
                friendsRelationshipSpi.setSelection(relationAdapter.getPosition(mFriends.getRelationship()));
            }
            friendsName.setText(mFriends.getName());
            friendsPhone.setText(CommUtil.prettyString(mFriends.getCellPhone(), null, true, 3, 4));
            mFriends.setOldCellPhone(mFriends.getCellPhone());
        } else {
            title.setText(getString(R.string.add_friend));
        }

        if (mFriends != null) {
            List<Device> devices = Session.getInstance().getMonitors();
            for (Device device : devices) {
                if (device.getImei().equals(mFriends.getSelfImeis())) {
                    friendsTerm.setSelection(friendsTermAdapter.getPosition(device.getName()));
                }
            }
        }
    }

    private void initEvent() {
        //complet.setOnClickListener(this);
        imbSelectPic.setOnClickListener(this);
        friendsPhone.addTextChangedListener(new PrettyTextChangeListener(3, 4));
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.imb_select_pic:
                break;
            /*case R.id.btn_complet:
                //完成

                break;*/
            default:

                break;
        }

    }

    @Override
    protected void setComplet() {
        if (mFriends == null) {
            mFriends = new TermFriend();
            mFriends.setName(name);
            mFriends.setCellPhone(phone);
            mFriends.setRelationship(relationship);
            mFriends.setSelfImeis(imeis);
            mFriends.setId(0);
        } else {
            mFriends.setName(name);
            mFriends.setCellPhone(phone);
            mFriends.setRelationship(relationship);
            mFriends.setSelfImeis(imeis);
        }
        if(CommUtil.isBlank(phone)||phone.length()<8) {
            DialogInterface.OnClickListener lis = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    addFriendsMessage(mFriends);
                    AppContext.getEventBus().post(mFriends, Constants.EVENT_TAG_UPDATE_ACCOUNT);
                }
            };
            CommDialogListener<AddGoodFriendsActivity> negLis=new CommDialogListener<AddGoodFriendsActivity>(this) {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    getActivity().resetLoading(false);
                }
            };
            Utils.showNotifyDialog(this, R.string.note, R.string.short_phone_note, R.string.confirm, R.string.cancel, lis, negLis, 0, null);
        }else{
            addFriendsMessage(mFriends);
            AppContext.getEventBus().post(mFriends, Constants.EVENT_TAG_UPDATE_ACCOUNT);
        }
    }

    @Override
    protected boolean checkIsOk() {
        name = friendsName.getText().toString();
        phone = friendsPhone.getText().toString().trim();
        phone = CommUtil.trimSeprator(phone, null);
        relationship = relationFIds.get(3/*friendsRelationshipSpi.getSelectedItemPosition()*/);

//        List<Device> devices = Session.getInstance().getMonitors();
//        if (friendsTerm.getSelectedItemPosition() > 0 && friendsTerm.getSelectedItemPosition() <= devices.size()) {
//            imeis = devices.get(friendsTerm.getSelectedItemPosition() - 1).getImei();
//        }

//        if (relationship.equals(getString(R.string.pl_select))) {
//            Toast.makeText(this, getString(R.string.rel_relation_not_null), Toast.LENGTH_SHORT).show();
//            return false;
//        }
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, R.string.please_input_name, Toast.LENGTH_SHORT).show();
            return false;
        }
        if (CommUtil.calcASCIILen(name) > Constants.MAX_WATCH_TITLE_DISPLAY_LEN) {
            Toast.makeText(this, getString(R.string.name_length_limit), Toast.LENGTH_LONG).show();
            return false;
        }
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, R.string.please_input_phone, Toast.LENGTH_SHORT).show();
            return false;
        }
        if (Constants.IS_CHINA_VERSION && !Utils.isChinaMobileNO(phone)) {
            CommUtil.showMsgShort(getString(R.string.not_china_mobile));
            return false;
        }
//        if (TextUtils.isEmpty(relationship)) {
//            Toast.makeText(this, R.string.please_input_relationship, Toast.LENGTH_SHORT).show();
//            return false;
//        }
        if (!Utils.isMobileNO(phone)) {
            Toast.makeText(this, getString(R.string.phone_format_error), Toast.LENGTH_SHORT).show();
            return false;
        }
//        if (CommUtil.isBlank(imeis)) {
//            CommUtil.showMsgShort(getString(R.string.rel_watch_not_null));
//            return false;
//        }
        return true;
    }

    /**
     * 添加好友信息 id为0表示增加用户  否则为修改
     *
     * @param fds
     */
    private void addFriendsMessage(final TermFriend fds) {


        Log.i(Constants.TAG, fds.toString());
        fds.friendsAddAndEdit(this, new HttpCallback() {
            @Override
            public void onStart() {
                CommUtil.showProcessing(getRootView(), true, true);
            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onSuccess(ResponseData obj) {
                CommUtil.hideProcessing();
                if (obj.getRetcode() == 1) {
                    Toast.makeText(AddGoodFriendsActivity.this, fds.getId() == 0 ? getString(R.string.add_friend_succ) : getString(R.string.updata_freind_msg_succ), Toast.LENGTH_SHORT).show();
                    TermFriend fd = new TermFriend(obj.getBody());
                    fd.setOldCellPhone(fds.getOldCellPhone());
                    AppContext.getEventBus().post(fd, Constants.EVENT_TAG_UPDATE_ACCOUNT);
                    AppContext.getEventBus().post(fd, Constants.EVENT_TAG_UPDATE_TEL_ACCOUNT);
//                    DialogInterface.OnClickListener positiveListener=new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
                            AddGoodFriendsActivity.this.finish();
//                        }
//                    };
//                    Utils.showNotifyDialog(AddGoodFriendsActivity.this, R.string.note, R.string.add_good_fd_note,R.string.known,0,positiveListener,null,0,null);
                } else {
                    Toast.makeText(AddGoodFriendsActivity.this, obj.getMsg(), Toast.LENGTH_SHORT).show();
                    resetLoading(false);
                }
            }

            @Override
            public void onFailure(String message) {
                resetLoading(false);
                CommUtil.hideProcessing();
                CommUtil.showMsgShort(message);
            }
        });

    }

    private void setBackData(TermFriend friends) {
        Intent intent = new Intent();
        intent.putExtra("friend", friends);
        setResult(RESULT_OK, intent);
    }

}
